package org.oimwrapper.connectors.common;

import java.sql.*;

import org.oimwrapper.connectors.*;

/**
 * Updates all process form versions to the active version.<p>
 *
 * This task does not expect any parameters in addition to the standard
 * parameters in the {@link OIMTaskBase} class.
 */
public class OIMUpdateFormVersions extends OIMTaskBase {

	/**
	 * True if a stop has been requested for this task.
	 */
	private boolean stop;
	
	/**
	 * Default constructor.
	 */
	public OIMUpdateFormVersions() {
		super("OIMWRAPPER.TASK");
	}
	
	/**
	 * This method is called by the scheduler to execute the task instance.
	 */
	public void execute() {
		try {
			Connection oimDB = getDirectDB();
			PreparedStatement query = oimDB.prepareStatement("select sdk_name, sdk_active_version from sdk where sdk_name like 'UD_%'");
			ResultSet forms = query.executeQuery();
			while (forms.next()) {
				String form = forms.getString("sdk_name");
				logger.debug("form = " + form);
				int version = forms.getInt("sdk_active_version");
				logger.debug("version = " + Integer.toString(version));
				PreparedStatement update = oimDB.prepareStatement("update " + form + " set " + form + "_version = ?");
				update.setInt(1, version);
				update.executeUpdate();
				oimDB.commit();
			}
			logger.warn("Updated all forms to the current active version.");
		} catch (Exception e) {
			OIMExceptionHandler.handleException(logger, e, getClass());
		}
	}
	
	/**
	 * This method is called by the scheduler to stop a running task instance.
	 * 
	 * @return <code>true</code>
	 */
	public boolean stop() {
		logger.warn(" ---- Stopping current task ---- ");
		stop = true;
		return stop;
	}
}